/*
 * Copyright 2011 es-planning Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package jp.arctos.ursus.extension.net.testutil;

import java.io.IOException;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SimpleSocketEchoServer {
    private ServerSocketChannel serverChannel;
    private ConcurrentLinkedQueue<SocketChannel> socketChannelQueue;
    private ExecutorService selectorService;
    private Selector selector;

    public SimpleSocketEchoServer(SocketAddress localAddress) throws Exception {
        socketChannelQueue = new ConcurrentLinkedQueue<SocketChannel>();
        init(localAddress);
    }

    protected void init(SocketAddress localAddress) throws Exception {
        try {
            serverChannel = ServerSocketChannel.open();
            serverChannel.configureBlocking(false);
            serverChannel.socket().setReuseAddress(true);
            serverChannel.socket().bind(localAddress);
            selector = Selector.open();
            serverChannel.register(selector, SelectionKey.OP_ACCEPT);

            SelectorRunner runner = new SelectorRunner();
            selectorService = Executors.newSingleThreadExecutor();
            selectorService.execute(runner);

        } catch (Exception e) {
            close();
            throw e;
        }
    }

    protected void onAcceptable(SelectionKey key) throws Exception {
        ServerSocketChannel channel = (ServerSocketChannel) key.channel();
        SocketChannel socketChannel = channel.accept();

        socketChannel.socket().setReuseAddress(true);
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);
        socketChannelQueue.offer(socketChannel);
    }

    protected void onReadable(SelectionKey key) throws Exception {
        SocketChannel channel = (SocketChannel) key.channel();

        ByteBuffer buffer = ByteBuffer.allocate(channel.socket().getReceiveBufferSize());
        int size = channel.read(buffer);
        if (size < 0) {
            // TODO Connection closed by peer.
            throw new IOException("Connection closed by peer");
        }

        buffer.flip();
        String str = decode(buffer);
        ByteBuffer retBuffer = pack(encode(str));
        channel.write(retBuffer);
    }

    public void close() {
        if (selectorService != null) {
            selectorService.shutdown();
        }

        for (SocketChannel channel : socketChannelQueue) {
            try {
                SelectionKey key = channel.keyFor(selector);
                if (key != null) {
                    key.cancel();
                }
                channel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (serverChannel != null) {
            try {
                SelectionKey key = serverChannel.keyFor(selector);
                if (key != null) {
                    key.cancel();
                }
                serverChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    protected String decode(ByteBuffer buffer) {
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
        return new String(bytes);
    }

    protected byte[] encode(String str) {
        return (str + "-server").getBytes();
    }

    protected ByteBuffer pack(byte[] bytes) {
        ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
        buffer.put(bytes);
        buffer.flip();
        return buffer;
    }

    class SelectorRunner implements Runnable {

        public void run() {
            for (; !selectorService.isShutdown();) {
                try {
                    int selected = selector.select();
                    if (selected > 0) {
                        Set<SelectionKey> selectedKeys = selector.selectedKeys();
                        Iterator<SelectionKey> iterator = selectedKeys.iterator();
                        while (iterator.hasNext()) {
                            SelectionKey key = iterator.next();
                            iterator.remove();

                            if (key.isValid() && key.isAcceptable()) {
                                onAcceptable(key);
                            }

                            if (key.isValid() && key.isReadable()) {
                                onReadable(key);
                            }
                        }
                    }
                } catch (Exception e) {
                    selectorService.shutdown();
                }
            }
        }
    }
}
